package com.lv.common.widget.recyclerview

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.recyclerview.widget.RecyclerView

/**
 * 作者： ygx
 * 创建日期：2025/8/11 下午2:08
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：自动滚动的recyclerview
 */
class AutoScrollRecyclerView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : RecyclerView(context, attrs, defStyle) {

    private var isOpenTimeHandler: Boolean = true

    val time: Long = 20// 缩短滚动间隔
    val scrollDistance: Int = 1 //单次滚动距离

    //这里也可选择直接使用TimerTask
    private val mTimeHandler: Handler by lazy {
        object : Handler(Looper.getMainLooper()) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                this@AutoScrollRecyclerView.scrollBy(scrollDistance, 0)
                if (isOpenTimeHandler) { // 如果允许滚动，则继续发送消息
                    //(this@AutoScrollRecyclerView.adapter as SpecialScrollChildAdapter).isAutoScroll(true)
                    mTimeHandler.sendEmptyMessageDelayed(0, time)
                }
            }
        }
    }

    //处理触摸停止滚动逻辑
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        val action = ev?.action
        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_OUTSIDE) {
            handleTimeHandler(true)
        } else if (action == MotionEvent.ACTION_DOWN) {
            handleTimeHandler(false)
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun onInterceptTouchEvent(e: MotionEvent): Boolean {
        return super.onInterceptTouchEvent(e)
    }

    override fun onTouchEvent(e: MotionEvent): Boolean {
        return super.onTouchEvent(e)
    }

    fun handleTimeHandler(isOpen: Boolean) {
        isOpenTimeHandler = isOpen
        mTimeHandler.removeMessages(0)
        if (isOpenTimeHandler) {
            mTimeHandler.sendEmptyMessageDelayed(0, 2000)
        } else {
            //(this@AutoScrollRecyclerView.adapter as SpecialScrollChildAdapter).isAutoScroll(false)
        }

    }

}
